package marchsoft.modules.selfFish.pisciculture.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.selfFish.pisciculture.entity.Water;
import marchsoft.modules.selfFish.pisciculture.entity.dto.WaterDto;
import marchsoft.modules.selfFish.pisciculture.entity.vo.WaterVo;
import marchsoft.modules.selfFish.pisciculture.mapper.WaterMapper;
import marchsoft.modules.selfFish.pisciculture.service.WaterService;
import marchsoft.modules.system.entity.SysRelationFile;
import marchsoft.modules.system.service.ISysRelationFileService;
import marchsoft.response.Result;
import marchsoft.utils.FileUtils;
import marchsoft.utils.SecurityUtils;
import marchsoft.utils.ServiceType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 *@title WaterServiceImpl
 *@description
 *@author Lenovo
 *@version 1.0
 *@create 2024-07-15 17:21
 */
@Service
@Slf4j
public class WaterServiceImpl extends ServiceImpl<WaterMapper, Water> implements WaterService {

    @Autowired
    private WaterMapper waterMapper;

    @Autowired
    private WaterService waterService;

    @Autowired
    private ISysRelationFileService sysRelationFileService;

    @Override
    public Result<Object> getWaterList(String waterTemperature, Long pageNum, Long pageSize) {
        IPage<WaterVo> waterList = waterMapper.getWaterList(new Page<>(pageNum, pageSize), waterTemperature);
        waterList.getRecords().forEach(healthVo -> {
            QueryWrapper<SysRelationFile> qw = new QueryWrapper<>();
            qw.eq("service_id",healthVo.getId());
            qw.eq("status","1");
            qw.eq("service_type", ServiceType.WATER);
            List<SysRelationFile> list = sysRelationFileService.list(qw);
            if(list != null && list.size()>0){
                healthVo.setFileId(list.get(0).getId());
            }

        });
        return Result.success(waterList);
    }

    @Override
    public Result<Object> create(WaterDto waterDto) {
        Water water = new Water();
        BeanUtils.copyProperties(waterDto,water);
        water.setCreatedUserId(SecurityUtils.getCurrentUserId());
        water.setCreatedTime(LocalDateTime.now());
        water.setStatus(true);
        if(waterMapper.insert(water)>0){
            //附件保存
            sysRelationFileService.saveFile(waterDto.getFileId(),water.getId(),ServiceType.WATER);
            log.info(StrUtil.format("【添加水质成功】操作人id：{}，新增目标watert：{}", SecurityUtils.getCurrentUserId(), waterDto));
            return Result.success("新增成功！");
        };
        return Result.error("新增失败！");
    }

    @Override
    public Result<Object> delete(Set<Long> ids) {
        UpdateWrapper<Water> uw = new UpdateWrapper<>();
        uw.in("id",ids)
                .set("status",false);
        if(waterService.update(uw)){
            //删除附件
            sysRelationFileService.deleteFile(new ArrayList<>(ids),ServiceType.WATER);
            log.info(StrUtil.format("【删除水质成功】操作人id：{}，删除目标waterts：{}", SecurityUtils.getCurrentUserId(), ids.toString()));
            return Result.success("删除成功！");
        };
        return Result.error("删除失败！");
    }

    @Override
    public Result<Object> update(WaterDto waterDto) {
        Water water = getById(waterDto.getId());
        if (ObjectUtil.isEmpty(water)) {
            log.error(StrUtil.format("【修改水质失败】操作人id：{}，修改目标water为空，目标waterId：{}", SecurityUtils.getCurrentUserId(), water.getId()));
            throw new BadRequestException("修改失败，当前数据id不存在");
        }
        if(water.getCreatedUserId()!=SecurityUtils.getCurrentUserId()){
            log.error(StrUtil.format("【修改水质失败】操作人id：{}，目标water新增人id：{}", SecurityUtils.getCurrentUserId(), water.getCreatedUserId()));
            throw new BadRequestException("该水质不是你新增的，不能修改：" + water.getId());
        }
        BeanUtils.copyProperties(waterDto,water);
        if(updateById(water)){
            //先删除
            sysRelationFileService.deleteFile(Arrays.asList(waterDto.getId()),ServiceType.WATER);
            //附件保存
            sysRelationFileService.saveFile(waterDto.getFileId(),water.getId(),ServiceType.WATER);
            log.info(StrUtil.format("【修改水质成功】操作人id：{}，修改目标water：{}", SecurityUtils.getCurrentUserId(), waterDto));
            return Result.success("修改成功！");
        };
        return Result.error("修改失败！");
    }

    @Override
    public void download(String waterTemperature, HttpServletResponse response) throws IOException {
        Page page = new Page<>(-1, -1);
        List<WaterVo> records = waterMapper.getWaterList(page, waterTemperature).getRecords();
        List<Map<String, Object>> list = new ArrayList<>();
        records.forEach(watertVo -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("清澈度", watertVo.getClarity());
            map.put("透明度", watertVo.getTransparency());
            map.put("气味", watertVo.getSmell());
            map.put("水色", watertVo.getWaterColor());
            map.put("PH值", watertVo.getPhValue());
            map.put("溶氧量", watertVo.getOxygenContent());
            map.put("水温", watertVo.getWaterTemperature());
            map.put("流动性", watertVo.getMobility());
            map.put("硬度", watertVo.getHardness());
            map.put("水位", watertVo.getWaterLevel());
            map.put("生物指标（如藻类，微生物）", watertVo.getBiologicalContent());
            //map.put("是否开启灯光照射", "");
            map.put("说明", watertVo.getDescription());
            map.put("创建时间", LocalDateTimeUtil.format(watertVo.getCreatedTime(), DatePattern.NORM_DATETIME_FORMATTER));
            list.add(map);
        });
        Map<Integer, Integer>widthMap = new HashMap<>();
        FileUtils.downloadExcel(list,widthMap, response);
    }
}
